package org.mybatis.jpetstore.test.socket;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;

public class ServerThread extends Thread {
	private Socket client;
	private int counter;
	
	public ServerThread(Socket client,int counter) throws UnknownHostException{
		System.out.println("Create connection with "+client.getInetAddress().getLocalHost().toString()+"successful.");
		this.client = client;
		this.counter = counter;
	}
	
	public void run(){
		try{
			BufferedInputStream bis = new BufferedInputStream(client.getInputStream());
			BufferedOutputStream bos = new BufferedOutputStream(client.getOutputStream());
			
			bos.write(("Hi! Enter Quit to exit.\r\n").getBytes());
			bos.flush();
			
			boolean done = false;
			byte[] bytes = new byte[client.getReceiveBufferSize()];
			while(!done){
				int contentLength = bis.read(bytes);
				
				if(contentLength == -1){
					System.out.println("contentLength = "+contentLength);
					done = true;
				}else{
					byte[] b1 = SocketUtil.getSubByte(bytes,0,4);
					byte[] b2 = SocketUtil.getSubByte(bytes,0,4);
					byte[] b3 = SocketUtil.getSubByte(bytes,0,4);
					System.out.println("111111111111:"+SocketUtil.byte2int(b1));
					System.out.println("报文长度"+SocketUtil.byte2int(b2));
					System.out.println("报文内容"+new String(b3,"ISO-8859-1"));
				}
			}
		}catch(Exception e){
			e.printStackTrace();
		}finally{
			try{
				if(client != null){
					client.close();
					System.out.println("Disconnect successful");
				}
			}catch(IOException e){
				e.printStackTrace();
			}
		}
	}

}
